package com.efounder.chat.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.efounder.chat.R;
import com.efounder.chat.adapter.AddGroupUserListAdapter;
import com.efounder.chat.adapter.AddPublicUserListGXAdapter;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.model.Group;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.efounder.view.LoadListView;
import com.utilcode.util.KeyboardUtils;

import java.util.ArrayList;
import java.util.List;

import static com.efounder.frame.utils.NetStateBroadcastReceiver.isNetActive;

/**
 * created by kongmeng on 2019/3/25
 * 添加好友，增加查询，分页，
 * 目前共享、中建使用
 */
public class AddAllTypeFriendsGX extends BaseActivity {

    private String searchKeyword;
    private int friendType;//朋友类型
    private static final int TYPE_PERSON = 0;
    private static final int TYPE_GROUP = 1;
    private static final int TYPE_OFFICAL_ACCOUNT = 2;
    private String hint;//搜索提示
    private List<User> accountUsers = new ArrayList<>();
    private List<Group> groupUsers = new ArrayList<>();
    InputMethodManager manager;
    AddPublicUserListGXAdapter adapter;
    private InputMethodManager imm;
    private RelativeLayout re_search;
    private TextView tv_search;
    private EditText et_search;
    private LoadListView listView;

    int startPage;//第几页
    int pageRow;//每页多少

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addfriends_gx);
        manager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        init();
    }

    private void init() {
        startPage = 1;
        pageRow = 10;
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        re_search = (RelativeLayout) findViewById(R.id.re_search);
        tv_search = (TextView) re_search.findViewById(R.id.tv_search);
        et_search = (EditText) findViewById(R.id.et_search);
        et_search.post(new Runnable() {
            @Override
            public void run() {
                et_search.setFocusableInTouchMode(true);
                et_search.requestFocus();
                KeyboardUtils.showSoftInput(et_search);
            }
        });
        listView = (LoadListView) findViewById(R.id.listView_addfriend);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            friendType = bundle.getInt("type", 0);
        }
        switch (friendType) {
            case TYPE_PERSON:
                hint = "用户名/手机号/公司/部门";
                break;
            case TYPE_GROUP:
                hint = getResources().getString(R.string.wechatview_serach_hint_group);
                break;
            case TYPE_OFFICAL_ACCOUNT:
                hint = ResStringUtil.getString(R.string.chat_search_app_number);
                break;
        }
        et_search.setHint(hint);

        listView.setInterface(new LoadListView.IloadListener() {
            @Override
            public void onLoad() {
                switch (friendType) {
                    case TYPE_PERSON:
                        try {
                            if (startPage < 1) {
                                return;
                            }
                            GetHttpUtil.searchFriendsFY(AddAllTypeFriendsGX.this, searchKeyword, startPage, pageRow, new GetHttpUtil.SearchFriendsCallBack() {
                                @Override
                                public void getFriendsSuccess(List<User> users, boolean isSuccess) {
                                    LoadingDataUtilBlack.dismiss();
                                    if (users.size() == 0) {
                                        Toast toast = Toast.makeText(AddAllTypeFriendsGX.this, R.string.chat_no_match_user, Toast.LENGTH_SHORT);
                                        toast.setGravity(Gravity.CENTER, 0, 0);
                                        toast.show();
                                    }
                                    listView.loadComplete();
//                                    accountUsers.clear();
                                    accountUsers.addAll(users);
                                    adapter.notifyDataSetChanged();
                                    startPage += 1;
//                                    generateFriendsAccountListView(accountUsers);
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                            LoadingDataUtilBlack.dismiss();
                        }
                        break;
                    case TYPE_GROUP:
                        LoadingDataUtilBlack.dismiss();
                        break;
                    case TYPE_OFFICAL_ACCOUNT:
                        LoadingDataUtilBlack.dismiss();
                        break;
                }
            }
        });

        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    re_search.setVisibility(View.VISIBLE);
                    tv_search.setText(et_search.getText().toString().trim());
                } else {
                    re_search.setVisibility(View.GONE);
                    tv_search.setText("");
                    List<User> userList = new ArrayList<>();
                    adapter = new AddPublicUserListGXAdapter(userList);
                    listView.setAdapter(adapter);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        et_search.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (i == KeyEvent.KEYCODE_ENTER && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    //先隐藏键盘
                    if (manager.isActive()) {
                        manager.hideSoftInputFromWindow(et_search.getApplicationWindowToken(), 0);
                    }
                    //自己需要的操作
                    serach();
                }
                return false;
            }
        });
        re_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                serach();
            }
        });

    }

    private void serach() {

        LoadingDataUtilBlack.show(AddAllTypeFriendsGX.this, ResStringUtil.getString(R.string.chat_searching));
        imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), InputMethodManager.SHOW_FORCED);
        searchKeyword = et_search.getText().toString().trim();
        if (searchKeyword.equals("")) {
            return;
        }
        if (!isNetActive()) {//无网络
            LoadingDataUtilBlack.dismiss();
            ToastUtil.showToast(AddAllTypeFriendsGX.this, R.string.common_text_network_error_please_again);
            return;
        }

        switch (friendType) {
            case TYPE_PERSON:
                try {
                    GetHttpUtil.searchFriendsGX(AddAllTypeFriendsGX.this, searchKeyword, new GetHttpUtil.SearchFriendsCallBack() {
                        @Override
                        public void getFriendsSuccess(List<User> users, boolean isSuccess) {
                            LoadingDataUtilBlack.dismiss();
                            if (users.size() == 0) {
                                Toast toast = Toast.makeText(AddAllTypeFriendsGX.this, R.string.chat_no_match_user, Toast.LENGTH_SHORT);
                                toast.setGravity(Gravity.CENTER, 0, 0);
                                toast.show();
                            }
                            accountUsers.clear();
                            accountUsers.addAll(users);
                            startPage = 2;
                            generateFriendsAccountListView(accountUsers);

                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    LoadingDataUtilBlack.dismiss();
                }
                // new AddPersonalFriendTask().execute();
                break;
            case TYPE_GROUP://搜索聊天群
                try {
                    GetHttpUtil.searchGroup(AddAllTypeFriendsGX.this, searchKeyword, new GetHttpUtil.SearchGroupCallback() {
                        @Override
                        public void getGroupSuccess(List<Group> groups, boolean isSuccess) {
                            LoadingDataUtilBlack.dismiss();
                            if (isSuccess) {
                                if (groups.size() == 0) {
                                    Toast.makeText(AddAllTypeFriendsGX.this, R.string.chat_no_match_user, Toast.LENGTH_SHORT).show();
                                }
                                groupUsers.clear();
                                groupUsers.addAll(groups);
                                generateGroupListView(groups);
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    LoadingDataUtilBlack.dismiss();
                }
                break;
            case TYPE_OFFICAL_ACCOUNT://搜索公众号
                try {
                    GetHttpUtil.searchPublicNumber(AddAllTypeFriendsGX.this, searchKeyword, new GetHttpUtil.SearchPublicNumberCallBack() {

                        @Override
                        public void getPublicSuccess(List<User> users, boolean isSuccess) {
                            LoadingDataUtilBlack.dismiss();
                            if (isSuccess) {
                                if (users.size() == 0) {
                                    Toast toast = Toast.makeText(AddAllTypeFriendsGX.this, R.string.chat_no_match_user, Toast.LENGTH_SHORT);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    toast.show();

                                }
                                accountUsers.clear();
                                accountUsers.addAll(users);
                                if (adapter != null) {
                                    adapter.notifyDataSetChanged();
                                }

                                generatePublicAccountListView(accountUsers);
                            }
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                    LoadingDataUtilBlack.dismiss();
                }
                break;
        }
    }

    /**
     * 公众号
     *
     * @param users
     */
    public void generatePublicAccountListView(final List<User> users) {

        adapter = new AddPublicUserListGXAdapter(users);
        listView.setAdapter(adapter);
        if (users.size() == 1) {
            Intent intent = new Intent(AddAllTypeFriendsGX.this,
                    AddPublicFriendInfoActivity.class);
            intent.putExtra("user", users.get(0));
            startActivity(intent);
            AddAllTypeFriendsGX.this.finish();
            return;
        }
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                Intent intent = new Intent(AddAllTypeFriendsGX.this,
                        AddPublicFriendInfoActivity.class);
                intent.putExtra("user", users.get(position));
                startActivity(intent);
                AddAllTypeFriendsGX.this.finish();
            }
        });

    }

    /**
     * 普通好友
     *
     * @param users
     */
    public void generateFriendsAccountListView(final List<User> users) {

        adapter = new AddPublicUserListGXAdapter(users);
        listView.setAdapter(adapter);
        if (users.size() == 1) {
            //User isExists = WeChatDBManager.getInstance().getOneFriendById(users.get(0).getId());
            boolean isFriend = WeChatDBManager.getInstance().queryIsFriend(users.get(0).getId());

            Intent intent = new Intent(AddAllTypeFriendsGX.this,
                    AddFriendUserDetailGXActivity.class);
            intent.putExtra("user", users.get(0));
            startActivity(intent);

            //查询数据库属否存在该好友，如果得到的昵称跟id相同，说明不存在该好友
            //if (isExists.getNickName().equals(String.valueOf(users.get(0).getId()))) {
//            if (!isFriend) {
            //如果是星际通讯搜索好友
//                if (EnvironmentVariable.getProperty(KEY_SETTING_APPID, "").equals(AppContext.getInstance()
//                        .getString(R.string.special_appid))) {
//                    Intent intent = new Intent();
//                    intent.putExtra("id", users.get(0).getId());
//                    ChatActivitySkipUtil.startUserInfoActivity(AddAllTypeFriendsGX.this, intent);
//                } else {
//                    Intent intent = new Intent(AddAllTypeFriendsGX.this,
//                            AddFriendUserDetailGXActivity.class);
//                    intent.putExtra("user", users.get(0));
//                    startActivity(intent);
//                }

//            } else {//本地存在该好友
//
//                //如果是星际通讯搜索好友
//                if (EnvironmentVariable.getProperty(KEY_SETTING_APPID, "").equals(AppContext.getInstance()
//                        .getString(R.string.special_appid))) {
//                    Intent intent = new Intent();
//                    intent.putExtra("id", users.get(0).getId());
//                    ChatActivitySkipUtil.startUserInfoActivity(AddAllTypeFriendsGX.this, intent);
//                } else {
//                    Intent intent = new Intent();
//                    intent.putExtra("id", users.get(0).getId());
//                    ChatActivitySkipUtil.startUserInfoActivity(AddAllTypeFriendsGX.this, intent);
//                }
//            }

        }
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                //如果是星际通讯搜索好友
//                if (EnvironmentVariable.getProperty(KEY_SETTING_APPID, "").equals(AppContext.getInstance()
//                        .getString(R.string.special_appid))) {
//                    Intent intent = new Intent();
//                    intent.putExtra("id", users.get(position).getId());
//                    ChatActivitySkipUtil.startUserInfoActivity(AddAllTypeFriendsGX.this, intent);
//                    return;
//                }
                Intent intent = new Intent(AddAllTypeFriendsGX.this, AddFriendUserDetailGXActivity.class);
                intent.putExtra("user", users.get(position));
                startActivity(intent);
            }
        });

    }

    public void generateGroupListView(final List<Group> groups) {
        if (groups.size() == 1) {
            Intent intent = new Intent(AddAllTypeFriendsGX.this,
                    AddGroupUserInfoActivity.class);
            Bundle bundle = new Bundle();
            String groupId = String.valueOf(groups.get(0).getGroupId());
            Group tempGroup = WeChatDBManager.getInstance().getGroupWithUsers(Integer.valueOf(groupId));
            bundle.putInt("id", Integer.valueOf(groupId));
            //进入群信息页，处理加群操作
            //如果数据库没有，则没有加入群，在新界面中处理
            if (String.valueOf(tempGroup.getGroupId()).equals(tempGroup.getGroupName())) {
                bundle.putBoolean("added", false);//是否加群
            } else {
                bundle.putBoolean("added", true);//是否加群
            }
            bundle.putString("avatar", groups.get(0).getAvatar());
            intent.putExtras(bundle);
            startActivity(intent);
            AddAllTypeFriendsGX.this.finish();
            return;
        }
        AddGroupUserListAdapter adapter = new AddGroupUserListAdapter(groups);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                Intent intent = new Intent(AddAllTypeFriendsGX.this,
                        AddGroupUserInfoActivity.class);
                Bundle bundle = new Bundle();
                String groupId = String.valueOf(groups.get(position).getGroupId());
                Group tempGroup = WeChatDBManager.getInstance().getGroupWithUsers(Integer.valueOf(groupId));
                bundle.putInt("id", Integer.valueOf(groupId));
                bundle.putString("avatar", groups.get(position).getAvatar());
                //进入群信息页，处理加群操作
                //如果数据库没有，则没有加入群，在新界面中处理
                if (String.valueOf(tempGroup.getGroupId()).equals(tempGroup.getGroupName())) {
                    bundle.putBoolean("added", false);//是否加群
                } else {
                    bundle.putBoolean("added", true);//是否加群
                }
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

    }

    @Override
    public void back(View view) {
        finish();
    }

}
